const router = require("koa-router")();
const UserModel = require("../../models/user");
const { mongoList } = require("../../static/data");
const ShoesModel = require("../../models/shoesList");
router.post("/api/cart", async ctx => {
    let { userID, shoesID, state, size, num } = ctx.request.body;
    if (state) {
        // state==true 加入购物车
        var shoesRes;
        for (let m of mongoList) {
            shoesRes = await ShoesModel(m).find({ _id: shoesID });
            // 搜到了就跳出循环
            if (shoesRes.length != 0) {
                break;
            }
        }

        shoesRes[0]._doc.num = Number(num);
        shoesRes[0]._doc.size = Number(size);
        await UserModel.findOneAndUpdate({ _id: userID }, {
            $push: { cart: shoesRes[0] }
        });
        var res = await UserModel.find({ _id: userID });
        ctx.body = {
            code: 200,
            res,
            msg: `已添加到购物车!`
        }
    } else {
        console.log("success");
        await UserModel.updateOne({ _id: userID }, { $pull: { cart: {_id: shoesID } } });
        var res = await UserModel.find({ _id: userID });
        ctx.body = {
            code: 200,
            res,
            msg: `已从购物车删除!`
        }
    }

})
module.exports = router;